/*************************************************************
   Copyright(C) 2022 by WuIslet
   All rights reserved.
   
   UnityEditorWindowHelper.cs
   UnityFramework
   
   Created by WuIslet on 2022-04-08.
   ref: https://gist.github.com/Syy9/c0df54799395f0437ef5933ac61ee374
   
*************************************************************/

using System;
using UnityEditor;
using UnityEngine;

public enum EditorWindowType
{
    Game,
    Scene,
    Hierarchy,
    Console,
    Inspector,
    Project,
}
public static class UnityEditorWindowHelper
{
    public static Type GetWindowType(EditorWindowType editorWindowType)
    {
        var assembly = typeof(UnityEditor.EditorWindow).Assembly;
        var type = assembly.GetType(Convert(editorWindowType));
        return type;
    }

    public static EditorWindow GetWindow(EditorWindowType editorWindowType)
    {
        var assembly = typeof(UnityEditor.EditorWindow).Assembly;
        var type = assembly.GetType(Convert(editorWindowType));
        return EditorWindow.GetWindow(type);
    }

    private static string Convert(EditorWindowType editorWindowType)
    {
        string name = string.Empty;
        switch (editorWindowType)
        {
            case EditorWindowType.Game:
                name = "UnityEditor.GameView";
                break;
            case EditorWindowType.Scene:
                name = "UnityEditor.SceneView";
                break;
            case EditorWindowType.Hierarchy:
                name = "UnityEditor.SceneHierarchyWindow";
                break;
            case EditorWindowType.Console:
                name = "UnityEditor.ConsoleWindow";
                break;
            case EditorWindowType.Inspector:
                name = "UnityEditor.InspectorWindow";
                break;
            case EditorWindowType.Project:
                name = "UnityEditor.ProjectBrowser";
                break;
            default:
                throw new NotImplementedException();
        }
        return name;
    }

    public static bool IsEditorWindowOpen(EditorWindowType editorWindowType)
    {
        var windows = Resources.FindObjectsOfTypeAll<EditorWindow>();
        if (windows != null && windows.Length > 0)
        {
            var editorType = GetWindowType(editorWindowType);
            var list = windows;
            for (int i = 0, len = list.Length; i < len; ++i)
            {
                var editorWindow = list[i];
                if (editorWindow.GetType() == editorType)
                {
                    return true;
                }
            }
        }
        return false;
    }
}
